package org.example.backend.Module.System.User.Controller;

import org.example.backend.Base.Response.JsonResult;
import org.example.backend.Base.Response.StatusCode;
import org.example.backend.Module.System.User.Pojo.DTO.UserLoginParams;
import org.example.backend.Module.System.User.Pojo.Entity.User;
import org.example.backend.Module.System.User.Pojo.DTO.UserLogin;
import org.example.backend.Module.System.User.Pojo.Vo.UserVo;
import org.example.backend.Module.System.User.Service.UserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/v1/user")
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private PasswordEncoder passwordEncoder;


    @PostMapping("/login")
    public JsonResult login(@RequestBody UserLoginParams params) {
        UserLogin login = this.userService.login(params.getUsername(), params.getPassword());

        return new JsonResult(StatusCode.LOGIN_SUCCESS, login);
    }

    @GetMapping("/myInfo")
    public JsonResult myInfo() {
        UserVo data = this.userService.myInfo();

        return JsonResult.ok(data);
    }


    @PreAuthorize("hasAuthority('user.list')")
    @GetMapping("/selectPage")
    public JsonResult selectPage() {
        return null;
    }

    @PreAuthorize("hasAuthority('user.add')")
    @PostMapping("/add")
    public JsonResult add(@RequestBody User user) {
        user.setId(null);
        user.setPassword(passwordEncoder.encode(user.getPassword()));

        this.userService.addOrUpdateUser(user);

        return JsonResult.ok();
    }

    @GetMapping("/get/{id}")
    public JsonResult get(@PathVariable Long id) {
        UserVo userVo = this.userService.getById(id);

        return userVo != null ? JsonResult.ok(userVo) : new JsonResult(StatusCode.DATA_UNEXISTS);
    }
}
